<template>
	<view class="container">
		<!-- 合同内容区域 -->
		<view class="contract-content">
			<view class="contract-header" v-if="!contractData.hideNameInDoc">
				<text class="contract-name">《{{ contractData.toolContractName }}》</text>
				<!-- <text class="contract-subtitle">合同编号：{{ contractData.toolContractCode }}</text> -->
			</view>

			<view class="contract-body">
				<block v-if="contractData.partySide==1">
					<view class="contract-text">
						<text>甲方：{{contractData.companyName}}</text>
					</view>
					<!-- <view class="contract-text">
						乙方：<view class="input-wrapper small">
							<view class="flex">
								<text>姓名：</text>
								<input class="input-field" v-model="postData.realName" placeholder="请输入姓名" />
							</view>
							<view class="flex">
								<text>身份证号：</text>
								<input class="input-field" v-model="postData.idNumber" placeholder="请输入身份证号" />
							</view>
						</view>
					</view> -->
				</block>
				<block v-else>
					<!-- <view class="contract-text">
						甲方：<view class="input-wrapper small">

							<view class="flex">
								<text>姓名：</text>
								<input class="input-field" v-model="postData.realName" placeholder="请输入姓名" />
							</view>
							<view class="flex">
								<text>身份证号：</text>
								<input class="input-field" v-model="postData.idNumber" placeholder="请输入身份证号" />
							</view>
							
						</view>
					</view> -->
					<view class="contract-text">
						<text>乙方：{{contractData.companyName}}</text>
					</view>
					
				</block>
				<view class="contract-title">
					<text>{{contractData.docTitle}}</text>
				</view>
				<!-- 注意：使用v-html需要确保内容来自可信源，避免XSS攻击 -->
				<!-- contractData.contractContent应在服务端进行严格的HTML过滤和安全处理 -->
				<view class="contract-text" v-if="contractData.contractContent && typeof contractData.contractContent === 'string'">
					<view v-html="contractData.contractContent"></view>
				</view>
				<view class="contract-text" v-else>合同内容加载中...</view>
				
				<view class="contract-text input-group flex">
					<text class="input-label">姓名：</text>
					<input class="input-field" v-model="postData.realName" placeholder="请输入姓名" />
				</view>
				<view class="contract-text input-group flex">
					<text class="input-label">身份证号：</text>
					<input class="input-field" v-model="postData.idNumber" placeholder="请输入身份证号" />
				</view>
				<view class="contract-text input-group flex" v-if="contractData.needWechat">
					<text class="input-label">微信号：</text>
					<input class="input-field" v-model="postData.wechatAccount" placeholder="请输入微信号" />
				</view>
				<view class="contract-text input-group flex" v-if="contractData.needContact||bindMobile==1">
					<text class="input-label">联系方式：</text>
					<input class="input-field" v-model="postData.mobile" placeholder="请输入手机号" />
				</view>
				<view class="contract-text input-group flex" v-if="contractData.needAddress">
					<text class="input-label">住址：</text>
					<input class="input-field" v-model="postData.address" placeholder="请输入住址" />	
				</view>
				<view class="contract-text">
					<text>备注：{{contractData.remark}}</text>
				</view>

				<view class="contract-signature-area">
					<text>{{contractData.partySide==1?'甲方':'乙方'}}签章：</text>
					<image :src="contractData.sealImageUrl" mode="aspectFit" class="stamp-image"></image>
				</view>
				<view class="contract-signature-area">
					<text>{{contractData.partySide==1?'乙方':'甲方'}}签章：</text>
					<view class="your-signature" v-if="signatureImage">
						<image :src="signatureImage" mode="aspectFit" class="signature-image"></image>
					</view>
					<text v-else class="no-signature">请在下方手写签名</text>
				</view>
				
				<view class="contract-date">
					<text>签署日期：{{ currentDate }}</text>
				</view>
			</view>
		</view>

		<!-- 手写签名区域 -->
		<view class="signature-container">
			<view class="signature-title">请在此处签名</view>
			<SignaturePad ref="sign" canvas-id="contractSignPad" :width="700" :height="300" pen-color="#000"
				background-color="#fafafa" />
			<view class="signature-buttons">
				<button @tap="clearSignature" class="clear-button">清除</button>
				<button @tap="saveSignature" class="save-button">确定</button>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="bottom-button">
			<button @tap="submitContract" class="submit-button" :disabled="!signatureImage">提交签署</button>
		</view>
	</view>
</template>

<script>
	import {
		getContractDetail,
		uploadSignature
	} from '@/api/contract';
	import requestFile from '@/utils/upFlie.js'
	import SignaturePad from '@/components/SignaturePad.vue'
	import {IdCardValidate} from '@/utils/validate.js'
	export default {
		data() {
				return {
					userInfo: uni.getStorageSync('userInfo'),
					contractId: '',
					contractTitle: '',
					contractNo: '',
					userName: '',
					contractData: {},
					currentDate: '',
					signatureImage: '',
					hasSigned: false,
					bindMobile:0,//是否绑定手机号，1：绑定
					postData:{
						// userContractId: '',//合同记录ID
						userId: '',//用户ID
						signImageUrl: '',//签名图片URL
						toolContractId: '',//合同模板ID
						realName: '',//真实姓名
						idNumber: '',//身份证号
						wechatAccount: '',//微信号
						mobile: '',//联系方式
						address: '',//住址
					}
					//todo 微信号、联系方式、住址接口不支持，暂不支持填写，签名图片需要上传接口再提交
				};
		},
		components: {
			SignaturePad
		},
		onLoad(options) {
			// 获取合同ID
			if (options.code) {
				this.contractId = options.code;
				this.getContractInfo();
			}
			if(options.bindMobile-0==1){
				this.bindMobile=1;
			}

			// 初始化日期
			const today = new Date();
			this.currentDate = today.getFullYear() + '-' + (today.getMonth() + 1).toString().padStart(2, '0') + '-' + today
				.getDate().toString().padStart(2, '0');

			// 组件挂载后由组件内部初始化
		},
		methods: {
			// 获取合同信息
			async getContractInfo() {
				try {
					const res = await getContractDetail({
						code: this.contractId
					});
					if (res.code === 0) {
						// 实际项目中，根据接口返回数据更新页面
						this.contractTitle = res.data.docTitle;
						this.contractNo = res.data.toolContractCode;
						this.postData.toolContractId = res.data.toolContractId;
						this.contractData = res.data
					}
				} catch (error) {
					console.error('获取合同信息失败', error);
					uni.showToast({
						title: '获取合同信息失败',
						icon: 'none'
					});
				}
			},

			// 清除签名
			clearSignature() {
				this.$refs.sign && this.$refs.sign.clear();
				this.signatureImage = '';
			},

			// 保存签名
			saveSignature() {
				if (!this.$refs.sign || !this.$refs.sign.hasSignature()) {
					uni.showToast({
						title: '请先完成签名',
						icon: 'none'
					})
					return
				}
				this.$refs.sign.toTempFilePath()
					.then((path) => {
						this.signatureImage = path
						this.hasSigned = true
						uni.showToast({
							title: '签名成功',
							icon: 'success'
						})
					})
					.catch((error) => {
						console.error('保存签名失败', error)
						uni.showToast({
							title: '保存签名失败',
							icon: 'none'
						})
					})
			},

			// 提交签署
			async submitContract() {
				if (!this.signatureImage) {
					uni.showToast({
						title: '请先完成签名',
						icon: 'none'
					});
					return;
				}

				if(this.contractData.needWechat && !this.postData.wechatAccount){
					uni.showToast({
						title: '请填写微信号',
						icon: 'none'
					});
					return;
				}
				const phoneReg=/^1[3-9]\d{9}$/
				if(this.contractData.needContact && !phoneReg.test(this.postData.mobile)){
					uni.showToast({
						title: '请填正确写联系方式',
						icon: 'none'
					});
					return;
				}
				if(this.contractData.needAddress && !this.postData.address){
					uni.showToast({
						title: '请填写住址',
						icon: 'none'
					});
					return;
				}
				if(!IdCardValidate(this.postData.idNumber)){
					uni.showToast({
						title: '请正确输入身份证号',
						icon: 'none'
					});
					return;
				}
				try {
					// 显示加载提示
					uni.showLoading({
						title: '提交中...'
					});
					const imgRes=await requestFile({
						base64:this.signatureImage,
						formData:{fileType:'contract'}
					})
					// 合同签署
					const res = await uploadSignature({
						...this.postData,
						userId: this.userInfo.userId,//用户ID
						signImageUrl: imgRes.data.data,//签名图片URL
					});

					// 隐藏加载提示
					uni.hideLoading();

					if (res.code === 0) {
						uni.showToast({
							title: '签署成功',
							icon: 'success'
						});

						// 签署成功后返回上一页或跳转到成功页面
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '签署失败',
							icon: 'none'
						});
					}
				} catch (error) {
					
					uni.hideLoading();
					console.error('提交签署失败', error);
					uni.showToast({
						title: '提交签署失败',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style scoped lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.navbar {
		height: 88rpx;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
	}

	.contract-content {
		flex: 1;
		// overflow-y: auto;
		padding: 50rpx;
		background-color: #ffffff;
		margin: 0 0 20px;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		ul{
			max-width: 100%;
		}
	}

	.contract-header {
		align-items: center;
		justify-content: space-between;
		text-align: center;
		margin-bottom: 40rpx;
	}

	.contract-name {
		font-size: 40rpx;
		font-weight: 600;
		color: #333333;
	}
	
	.contract-subtitle {
		font-size: 28rpx;
		color: #666666;
	}

	.contract-body {
		width: 100%;
		box-sizing: border-box;
		line-height: 1.8;
	}
	.contract-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
	}
	.contract-text {
		margin-bottom: 20rpx;
		font-size: 30rpx;
		color: #333333;
	}
	
	.small{
		.input-wrapper{
			padding-left: 30px;
		}
	}
	.flex{
		margin-left: 40px;
		display: flex;
		align-items: center;
		line-height: 30px;
		border-bottom: 1px solid #e0e0e0;
		input{
			flex: 1;
			border: none;
		}
	}

	.contract-signature-area {
		margin-top: 40rpx;
		display: flex;
		align-items: center;
		font-size: 30rpx;
		color: #333333;
	}

	.input-group {
		display: flex;
		align-items: flex-start;
		margin-top: 20rpx;
		margin-left: 0!important;
	}

	.input-label {
		font-size: 28rpx;
		color: #333333;
		width: 160rpx;
		flex-shrink: 0;
		padding-top: 8rpx;
	}

	.input-wrapper {
		flex: 1;
		position: relative;
	}

	.input-field {
		width: 100%;
		font-size: 28rpx;
		color: #333333;
		padding: 8rpx 0;
		background-color: transparent;
		border: none;
		height: 40px;
		box-sizing: border-box;
		border-bottom: 1px solid #ccc;
	}

	.input-line {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 1rpx;
		background-color: #e0e0e0;
	}

	.stamp-image {
		width: 200rpx;
		height: 200rpx;
		margin-left: 20rpx;
	}

	.your-signature {
		margin-left: 20rpx;
		width: 200rpx;
		height: 100rpx;
		border: 1rpx solid #e0e0e0;
	}

	.signature-image {
		width: 100%;
		height: 100%;
	}

	.no-signature {
		margin-left: 20rpx;
		font-size: 28rpx;
		color: #999999;
	}

	.contract-date {
		margin-top: 40rpx;
		text-align: right;
		font-size: 30rpx;
		color: #333333;
	}

	.signature-container {
		background-color: #ffffff;
		margin: 0 20rpx 20rpx 20rpx;
		padding: 30rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.signature-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.signature-canvas {
		width: 100%;
		height: 200rpx;
		border: 1rpx solid #e0e0e0;
		background-color: #fafafa;
	}

	.signature-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
	}

	.clear-button {
		flex: 1;
		height: 80rpx;
		background-color: #ffffff;
		color: #666666;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		margin-right: 20rpx;
		font-size: 30rpx;
	}

	.save-button {
		flex: 1;
		height: 80rpx;
		background-color: #667eea;
		color: #ffffff;
		border-radius: 8rpx;
		font-size: 30rpx;
	}

	.bottom-button {
		padding: 30rpx;
		padding-bottom: 60rpx;
		background-color: #ffffff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.submit-button {
		width: 100%;
		height: 90rpx;
		background-color: #667eea;
		color: #ffffff;
		border-radius: 45rpx;
		font-size: 34rpx;
		font-weight: 600;
	}

	button[disabled] {
		background-color: #cccccc !important;
		color: #ffffff !important;
	}

	button::after {
		border: none !important;
	}
</style>